import org.junit.Test;
import test.ListNode;

/**
 * 6  给你一个链表节点,head,输入链表中倒数地k个节点
 */
public class kthNodeFromEnd {

    @Test
    public void clibe() {
        ListNode list1 = new ListNode(6);
        list1.setNext(new ListNode(0));
        list1.setNext(new ListNode(11));
        list1.setNext(new ListNode(8));
        list1.setNext(new ListNode(9));
        list1.setNext(new ListNode(5));
        System.out.println(test1(list1,0));
    }

    public ListNode test1(ListNode head, int kthNode) {
        if (kthNode <= 0 || head == null) return null;
        ListNode pTemp = head, pKthNode = null;
        for (int count = 1; count < kthNode; count++) {
            if (pTemp != null) {
                pTemp = pKthNode.getNext();
            }
        }
        while (pTemp != null) {
            if (pKthNode == null) {
                pKthNode = head;
            } else {
                pKthNode = pKthNode.getNext();
                pTemp = pTemp.getNext();
            }
        }
        if (pKthNode != null) {
            return pKthNode;
        }
        return null;
    }
}
